package com.itheima.controller;
import com.alibaba.excel.EasyExcel;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Dto.OrdersDto;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.*;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.UserService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import jdk.net.SocketFlow;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;



    //去支付生成订单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("下单成功");
    }


    //分页查询订单
    public List<OrderDetail> getOrderDetailById(Long OrderId){
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,OrderId);
        List<OrderDetail> list = orderDetailService.list(wrapper);
        return list;
    }


    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage, wrapper);


        LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
        List<Orders> records = ordersPage.getRecords();
       List<OrdersDto> ordersDtoList= records.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            Long orderId = item.getId();

            List<OrderDetail> orderDetailById = this.getOrderDetailById(orderId);
            BeanUtils.copyProperties(item,ordersDto);
            ordersDto.setOrderDetails(orderDetailById);
            return ordersDto;
        }).collect(Collectors.toList());


        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);

//        return R.success(ordersPage);
    }


    //客户端订单显示
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {

        Page<Orders> pageInfor = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        wrapper.gt(StringUtils.isNotEmpty(beginTime), Orders:: getOrderTime, beginTime);
        wrapper.lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);

        ordersService.page(pageInfor, wrapper);
        return R.success(pageInfor);

    }


//    派送
   @PutMapping
    public R<String> statusa(@RequestBody Orders orders){
       Long id = orders.getId();
       LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
       wrapper.eq(Orders::getId,id);


       List<Orders> list = ordersService.list(wrapper);
       for (Orders orders1 : list) {
           Integer status = orders1.getStatus();
           if (status==2){
              orders1.setStatus(status+1);
           }
           ordersService.updateById(orders1);
           if (status==3){
               orders1.setStatus(status+1);
           }
           ordersService.updateById(orders1);


       } return R.success("成功");
   }


   //写出easy excel
   @GetMapping("/export")
   public void upload(HttpServletResponse response) throws IOException {
        //获取前端数据，放入list集合中
       List<Orders> list = ordersService.list();
        //item是所有数据中的一条数据
       List<Excel> excelList = list.stream().map((item) -> {
           Excel excel = Excel.builder().number(item.getNumber())
                   .phone(item.getPhone()).address(item.getAddress())
                   .orderTime(item.getOrderTime()).amount(item.getAmount()).build();
           if(item.getStatus()==2){
               excel.setStatus("派送");
           }else if(item.getStatus()==4){
               excel.setStatus("完成");
           }
           excel.setUserName(item.getConsignee());
           return excel;
       }).collect(Collectors.toList());
//        log.info("{}",biaoList);
       response.setHeader("Content-Disposition","attachment;filename=orderDetails.xlsx");
       EasyExcel.write(response.getOutputStream(),Excel.class)
               .sheet("明细")
               .doWrite(excelList);
   }
}
